package com.example.supernote.ui.utils

import androidx.activity.compose.ManagedActivityResultLauncher
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import com.example.supernote.R
import com.example.supernote.ui.components.UniformToast

/**
 * 一次只能请求一个权限...
 *
 * @param isGrantedRoute 请求权限成功后的执行函数
 * @param unGrantedRoute 请求权限失败后的执行函数，默认为空
 *
 * @return 权限执行器，获取之后调用 .launch(权限名称) 即可请求目标权限
 */
@Composable
fun getPermissionLauncher (
    isGrantedRoute: () -> Unit,
    unGrantedRoute: () -> Unit = {}
): ManagedActivityResultLauncher<String, Boolean> {
    val toastContext = LocalContext.current
    val warn = stringResource(R.string.permission_deny)
    return rememberLauncherForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted: Boolean ->
        if (isGranted) {
            isGrantedRoute()
        } else {
            unGrantedRoute()
            UniformToast(toastContext, warn, 80)
        }
    }
}